package com.voxel.sense.infomsg.module.message;

import android.os.Handler;
import android.support.v7.util.DiffUtil;

import com.example.com.common.app.BaseSourcePresenter;
import com.example.com.common.factory.data.DbDataSource;
import com.example.com.common.view.recycler.RecyclerAdapter;
import com.example.com.common.widget.diffui.DiffUiDataCallBack;

import java.util.List;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.model.db.MessageModle;
import cyy.example.com.facotry.net.RequestIdFactory;

/**
 * Created by ChenYiYao on 2018/12/3.
 * des : 消息模块p层
 */
public class MessagePresenter extends BaseSourcePresenter<MessageModle, MsgRepository, MessageContract.View>
        implements MessageContract.Presenter, DbDataSource.SucceedCallback<List<MessageModle>> {


    public MessagePresenter(MsgRepository source, MessageContract.View view) {
        super(source, view);
    }

    @Override
    public void onDataLoaded(final List<MessageModle> data, int reqId) {
        //使用diff工具进行增量刷新
        Factory.runOnAsync(new Runnable() {
            @Override
            public void run() {

                final RecyclerAdapter<MessageModle> adapter = mView.getRecyclerViewAdapter();

                DiffUiDataCallBack<MessageModle> callback = new DiffUiDataCallBack<MessageModle>(adapter.getItems(), data);
                final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(callback);
                //刷新界面回到主线程
                new Handler(Factory.app().getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        diffResult.dispatchUpdatesTo(adapter);
                        adapter.getItems().clear();
                        adapter.getItems().addAll(data);
                        mView.onAdapterDataChanged();
                    }
                });
            }
        });
    }

    @Override
    public void doCleanMsgData() {
        mSource.deleteTable();
    }

    @Override
    public void loadSource() {
        mSource.load(this, RequestIdFactory.LOAD_DB_MESSAGE_TABLE);
    }
}
